package com.ganbo.pattern.flyweight;

import lombok.Data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
import java.util.Vector;

/**
 * 享元模式(对象池)
 * Created by gan on 2020/6/11 23:27.
 */

@Data
public class ConnectionPool {

    private List<Connection> connections = new Vector<Connection>();

    private int poolSize = 5;
    private String url;
    private String password;
    private String userName;

    public ConnectionPool() {
        try {
            Class.forName("com.jdbc.mysql.Driver");
            Connection connection;
            for (int i = 0; i < poolSize; i++) {
                connection = DriverManager.getConnection(url, userName, password);
                connections.add(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     */
    public Connection getConnection() {
        return connections.get(0);
    }

    /**
     * 释放连接
     */
    public boolean relealse(Connection connection) {
        return connections.add(connection);
    }
}
